<template>
  <div class="register-container">
    <el-card class="register-card" shadow="hover">
      <div class="title">
        <h2>用户注册</h2>
      </div>
      
      <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="请输入用户名" 
            prefix-icon="el-icon-user"
            clearable>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password" 
            placeholder="请输入密码" 
            prefix-icon="el-icon-lock"
            show-password>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入密码" 
            prefix-icon="el-icon-key"
            show-password>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="请输入邮箱" 
            prefix-icon="el-icon-message"
            clearable>
          </el-input>
        </el-form-item>
        
        <el-form-item prop="phone">
          <el-input 
            v-model="registerForm.phone" 
            placeholder="请输入手机号" 
            prefix-icon="el-icon-mobile-phone"
            clearable>
          </el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button 
            type="primary" 
            :loading="loading" 
            @click="handleRegister" 
            class="register-button">
            注册
          </el-button>
        </el-form-item>
        
        <div class="tips">
          <span>已有账号？<router-link to="/login">立即登录</router-link></span>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { register, checkUsername, checkEmail } from '@/api/auth'

export default {
  name: 'Register',
  data() {
    // 自定义校验规则
    const validateUsername = (rule, value, callback) => {
      if (value.length < 4) {
        callback(new Error('用户名长度必须大于等于4位'))
      } else {
        checkUsername(value).then(response => {
          if (response.data) {
            callback(new Error('该用户名已被注册'))
          } else {
            callback()
          }
        }).catch(() => {
          callback()
        })
      }
    }
    
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('密码长度必须大于等于6位'))
      } else {
        if (this.registerForm.confirmPassword !== '') {
          this.$refs.registerForm.validateField('confirmPassword')
        }
        callback()
      }
    }
    
    const validateConfirmPassword = (rule, value, callback) => {
      if (value !== this.registerForm.password) {
        callback(new Error('两次输入的密码不一致'))
      } else {
        callback()
      }
    }
    
    const validateEmail = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(value)) {
        callback(new Error('请输入有效的邮箱地址'))
      } else {
        checkEmail(value).then(response => {
          if (response.data) {
            callback(new Error('该邮箱已被注册'))
          } else {
            callback()
          }
        }).catch(() => {
          callback()
        })
      }
    }
    
    const validatePhone = (rule, value, callback) => {
      const phoneRegex = /^1[3-9]\d{9}$/
      if (value && !phoneRegex.test(value)) {
        callback(new Error('请输入有效的手机号码'))
      } else {
        callback()
      }
    }
    
    return {
      registerForm: {
        username: '',
        password: '',
        confirmPassword: '',
        email: '',
        phone: ''
      },
      registerRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { validator: validateUsername, trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: validatePassword, trigger: 'blur' }
        ],
        confirmPassword: [
          { required: true, message: '请再次输入密码', trigger: 'blur' },
          { validator: validateConfirmPassword, trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: validateEmail, trigger: 'blur' }
        ],
        phone: [
          { validator: validatePhone, trigger: 'blur' }
        ]
      },
      loading: false
    }
  },
  methods: {
    handleRegister() {
      this.$refs.registerForm.validate(async valid => {
        if (valid) {
          this.loading = true
          try {
            const response = await register(this.registerForm)
            
            if (response.code === 200) {
              this.$message({
                message: '注册成功，请登录',
                type: 'success'
              })
              // 跳转到登录页
              this.$router.push('/login')
            } else {
              this.$message.error(response.message || '注册失败')
            }
          } catch (error) {
            console.error('注册失败', error)
            this.$message.error(`注册失败：${error.message || '未知错误'}`)
          } finally {
            this.loading = false
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  padding: 50px 0;
  background-color: #f5f7fa;
  background-image: linear-gradient(to bottom right, #EDF2F7, #E2E8F0);
}

.register-card {
  width: 450px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 30px;
  color: #303133;
}

.register-form {
  padding: 0 20px;
}

.register-button {
  width: 100%;
  border-radius: 4px;
  font-size: 16px;
  height: 44px;
  margin-top: 10px;
}

.tips {
  text-align: center;
  margin-top: 20px;
  color: #606266;
  font-size: 14px;
}

.tips a {
  color: #409EFF;
  text-decoration: none;
  font-weight: bold;
}

.tips a:hover {
  text-decoration: underline;
}

/* 输入框样式优化 */
/deep/ .el-input__inner {
  height: 44px;
  line-height: 44px;
}

/deep/ .el-form-item {
  margin-bottom: 22px;
}
</style> 